package user

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/userServiceClient/userrpc"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserDetailLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserDetailLogic {
	return &UserDetailLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserDetailLogic) UserDetail(req *types.UserDetailRequest) (resp *types.UserDetailResponse, err error) {
	// 获取基本信息
	usersDetail, err := l.svcCtx.UserServiceRPC.UserDetail(l.ctx, &userrpc.UserDetailRequest{
		UserId:    req.Id,
		StartTime: req.StartTime,
		EndTime:   req.EndTime,
	})
	if err != nil {
		return nil, err
	}

	resp = &types.UserDetailResponse{
		AgentInfo:           l.getAgentInfo(req.Id, usersDetail),
		DepositWithdrawal:   l.getDepositWithdrawal(req.Id, usersDetail),
		ActivityReward:      l.getActivityReward(req.Id, usersDetail),
		VipInfo:             l.getVipInfo(req.Id, usersDetail),
		SafeBox:             l.getSafeBox(req.Id, usersDetail),
		Balance:             l.getBalance(req.Id, usersDetail),
		Code:                l.getCode(req.Id, usersDetail),
		AccountData:         l.getAccountData(req.Id, usersDetail),
		LastThreeCharge:     l.getLastThreeCharge(req.Id, usersDetail),
		LastThreeWithdrawal: l.getLastThreeWithdrawal(req.Id, usersDetail),
		UserLoginLog:        l.getUserLoginLog(req.Id, usersDetail),
		UserRegisterLog:     l.getUserRegisterLog(req.Id, usersDetail),
		MemberBetInfo:       l.getMemberBetInfo(req.Id, usersDetail),
	}

	return
}

func (l *UserDetailLogic) getAgentInfo(id int64, userDetail *userrpc.UserDetailResponse) *types.AgentInfo {
	return &types.AgentInfo{
		TotalCommission:      userDetail.AgentInfo.BrokerAmount,
		InviteReward:         userDetail.AgentInfo.InviteAward,
		SubordinateCount:     int64(userDetail.AgentInfo.AllChildNum),
		IsReceivedCommission: userDetail.AgentInfo.RebatesStatus == 1,
	}
}

func (l *UserDetailLogic) getDepositWithdrawal(id int64, userDetail *userrpc.UserDetailResponse) *types.DepositWithdrawal {
	return &types.DepositWithdrawal{
		ManualDepositCount:    userDetail.RechargeAndWithdrawInfo.ManualRechargeCount,
		ManualDepositAmount:   userDetail.RechargeAndWithdrawInfo.ManualRechargeAmount,
		DepositBonus:          userDetail.RechargeAndWithdrawInfo.DepositBonus,
		TotalDepositCount:     userDetail.RechargeAndWithdrawInfo.RechargeCount,
		TotalDepositAmount:    userDetail.RechargeAndWithdrawInfo.RechargeAmount,
		TotalBonus:            0, // todo 彩金奖励暂时无
		TotalWithdrawalAmount: userDetail.RechargeAndWithdrawInfo.WithdrawAmount,
		TotalWithdrawalCount:  userDetail.RechargeAndWithdrawInfo.WithdrawCount,
		WaitOut:               userDetail.RechargeAndWithdrawInfo.WaitOut,
		TotalDepositDiff:      userDetail.RechargeAndWithdrawInfo.WithdrawDiff,
		TotalWithdrawalFee:    userDetail.RechargeAndWithdrawInfo.TotalWithdrawalFee,
	}
}

func (l *UserDetailLogic) getActivityReward(id int64, userDetail *userrpc.UserDetailResponse) *types.ActivityReward {
	// EventInfo
	return &types.ActivityReward{
		ReceivedRedPacket:      userDetail.ActiveRes.RedPacket,
		WeeklyReward:           userDetail.ActiveRes.WeekAward,
		DailyReward:            userDetail.ActiveRes.DayAward,
		SuperReward:            userDetail.ActiveRes.SuperAward,
		ChampionReward:         userDetail.ActiveRes.TournamentAward,
		RegisterReward:         userDetail.ActiveRes.RegisterAward,
		FirstChargeReward:      userDetail.ActiveRes.FirstChargeAward,
		DailySignReward:        userDetail.ActiveRes.SignInAward,
		NoviceReward:           userDetail.ActiveRes.NewHandAward,
		AgentRedPacketRecharge: userDetail.ActiveRes.AgentRedPacket,
		NewMemberReward:        userDetail.ActiveRes.NewMemberAward,
		LuckyDraw:              userDetail.ActiveRes.BigWheel,
	}
}

func (l *UserDetailLogic) getVipInfo(id int64, userDetail *userrpc.UserDetailResponse) *types.VipInfo {
	return &types.VipInfo{
		VipExp:                 userDetail.VipInfo.Exp,
		VipLevel:               int64(userDetail.VipInfo.VipLevel),
		VipMonthlyReward:       userDetail.VipInfo.MonthlyAwardAmount,
		VipMonthlyRewardCount:  userDetail.VipInfo.MonthlyAwardCount,
		VipUpgradePackage:      userDetail.VipInfo.UpgradeAwardAmount,
		VipUpgradePackageCount: userDetail.VipInfo.UpgradeAwardCount,
	}
}

func (l *UserDetailLogic) getSafeBox(userId int64, userDetail *userrpc.UserDetailResponse) *types.SafeBox {
	return &types.SafeBox{
		ReceivedBenefit: userDetail.SafeInfo.IncomeTotal,
		PendingBenefit:  userDetail.SafeInfo.PaddingIncome,
		InsuranceRate:   userDetail.SafeInfo.Rate,
	}
}

func (l *UserDetailLogic) getBalance(id int64, userDetail *userrpc.UserDetailResponse) *types.Balance {
	return &types.Balance{
		Balance:        userDetail.BalanceInfo.Balance,
		SafeBoxBalance: userDetail.BalanceInfo.SafeBalance,
		PendingBet:     userDetail.BalanceInfo.PendingBet,
	}
}

func (l *UserDetailLogic) getCode(id int64, userDetail *userrpc.UserDetailResponse) *types.Code {
	return &types.Code{
		TotalCodeCount:   userDetail.UserCodeInfo.NeedCode,
		NeedCodeCount:    userDetail.UserCodeInfo.AddCode,
		VipWashCodeCount: userDetail.UserCodeInfo.MemberCode,
		AntiWater:        userDetail.UserCodeInfo.BackAmount,
	}
}

func (l *UserDetailLogic) getAccountData(id int64, userDetail *userrpc.UserDetailResponse) *types.AccountData {
	return &types.AccountData{
		ParentAgentId:      userDetail.BaseInfo.ParentId,
		UserId:             userDetail.BaseInfo.UserId,
		Account:            userDetail.BaseInfo.Account,
		IsEffective:        userDetail.BaseInfo.Status == 0,
		RechargeLevel:      0, // todo  暂时没有
		BindEmail:          userDetail.BaseInfo.Email,
		BindMobile:         userDetail.BaseInfo.Phone,
		Integral:           0, // todo 没有
		FirstLoginTime:     userDetail.BaseInfo.FirstLoginTime,
		FirstChargeAmount:  userDetail.BaseInfo.FirstRechargeAmount,
		SecondChargeAmount: userDetail.BaseInfo.SecondRechargeAmount,
		ThreeChargeAmount:  userDetail.BaseInfo.ThirdRechargeAmount,
		RegisterTime:       userDetail.BaseInfo.RegisterTime,
		FirstChargeDate:    userDetail.BaseInfo.FirstRechargeTime,
		SecondChargeDate:   userDetail.BaseInfo.SecondRechargeTime,
		ThreeChargeDate:    userDetail.BaseInfo.ThirdRechargeTime,
		Remark:             userDetail.BaseInfo.Remark,
		CodeCount:          userDetail.UserCodeInfo.NeedCode,
	}
}

func (l *UserDetailLogic) getLastThreeCharge(id int64, userDetail *userrpc.UserDetailResponse) *types.LastThreeCharge {
	rechargeInfos := make([]*types.ChargeInfo, len(userDetail.RechargeInfo))
	for i, info := range userDetail.RechargeInfo {
		rechargeInfos[i] = &types.ChargeInfo{
			ChargeTime:   info.CreatedAt,
			ChargeAmount: info.Amount,
			ChargeType:   int64(info.Type),
		}
	}
	return &types.LastThreeCharge{
		Info: rechargeInfos,
	}
}

func (l *UserDetailLogic) getLastThreeWithdrawal(id int64, userDetail *userrpc.UserDetailResponse) *types.LastThreeWithdrawal {
	infos := make([]*types.Withdrawal, len(userDetail.WithdrawInfo))
	for i, info := range userDetail.WithdrawInfo {
		infos[i] = &types.Withdrawal{
			WithdrawalTime:   info.CreatedAt,
			WithdrawalAmount: info.Amount,
			WithdrawalType:   int64(info.Type),
		}
	}

	return &types.LastThreeWithdrawal{
		Info: infos,
	}
}

func (l *UserDetailLogic) getUserLoginLog(id int64, userDetail *userrpc.UserDetailResponse) *types.UserLoginLog {
	loginInfo := make([]*types.LoginInfo, len(userDetail.LoginInfo))
	for i, info := range userDetail.LoginInfo {
		loginInfo[i] = &types.LoginInfo{
			LoginTime:   info.LoginAt,
			LoginIp:     info.Ip,
			SameIpCount: info.Count,
		}
	}
	return &types.UserLoginLog{
		Info: loginInfo,
	}
}

func (l *UserDetailLogic) getUserRegisterLog(id int64, userDetail *userrpc.UserDetailResponse) *types.UserRegisterLog {
	registerInfo := make([]*types.RegisterInfo, 1)
	registerInfo[0] = &types.RegisterInfo{
		RegisterTime:    userDetail.RegisterInfo.RegisterTime,
		RegisterIp:      userDetail.RegisterInfo.RegisterIp,
		RegisterIpCount: userDetail.RegisterInfo.Count,
	}
	return &types.UserRegisterLog{
		Info: registerInfo,
	}
}

func (l *UserDetailLogic) getMemberBetInfo(id int64, userDetail *userrpc.UserDetailResponse) *types.MemberBetInfo {
	var totalBetAmount float64
	var totalFee float64
	var totalProfit float64
	var totalOrderCount int64

	infos := make([]*types.GameBetInfo, len(userDetail.GameStatInfo)+len(userDetail.GameTypeStatInfo))
	i := 0
	for _, info := range userDetail.GameStatInfo {
		infos[i] = &types.GameBetInfo{
			GameName:   info.GameName,
			BetAmount:  info.BetAmount,
			Fee:        info.ServiceChagreAmount,
			Profit:     info.ProfitAmount,
			OrderCount: info.OrderNum,
		}
		i++
		totalBetAmount += info.BetAmount
		totalFee += info.ServiceChagreAmount
		totalProfit += info.ProfitAmount
		totalOrderCount += info.OrderNum
	}
	for _, info := range userDetail.GameTypeStatInfo {
		infos[i] = &types.GameBetInfo{
			GameName:   info.CategoryName,
			BetAmount:  info.BetAmount,
			Fee:        info.ServiceChagreAmount,
			Profit:     info.ProfitAmount,
			OrderCount: info.OrderNum,
		}
		totalBetAmount += info.BetAmount
		totalFee += info.ServiceChagreAmount
		totalProfit += info.ProfitAmount
		totalOrderCount += info.OrderNum
		i++
	}

	return &types.MemberBetInfo{
		Info:            infos,
		TotalBetAmount:  totalBetAmount,
		TotalFee:        totalFee,
		TotalProfit:     totalProfit,
		TotalOrderCount: totalOrderCount,
	}
}
